package com.racetime.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.racetime.po.Date;
import com.racetime.service.DateService;
import com.racetime.serviceImpl.DateServiceImpl;
import com.racetime.util.JsonUtil;
import com.racetime.util.MyLogger;
import com.racetime.util.ServiceAgent;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

/**
 * @author : Ice'Clean
 * @date : 2021-05-24
 *
 * 接收所有与日程有关的请求
 */
public class DateServlet extends BaseServlet{

    Logger servletLogger = MyLogger.getLogger("servlet");
    Logger dateLogger = MyLogger.getLogger("date");

    /**
     * 日程服务的动态代理
     */
    DateService dateService = (DateService) new ServiceAgent(new DateServiceImpl()).getAgent();

    /**
     * 获取请求体中可能有的全部日程信息
     * 其中 userId, dateId, dateFinish 根据需要选填，其他必含
     * @param request 目标请求
     * @return 包含了请求信息的日程实例对象
     */
    private Date getDateByRequest(HttpServletRequest request) {
        Date date = new Date();

        // 获取可能存在的 userId 和 dateId
        String userId = request.getParameter("userId");
        String dateId = request.getParameter("dateId");

        if (userId != null) {
            date.setUserId(Integer.parseInt(userId));
        }

        if (dateId != null) {
            date.setDateId(Integer.parseInt(dateId));
        }

        date.setDateName(request.getParameter("dateName"));
        date.setDateContent(request.getParameter("dateContent"));
        date.setDateClass(request.getParameter("dateClass"));
        date.setDateLevel(Integer.parseInt(request.getParameter("dateLevel")));
        date.setDateStart(request.getParameter("dateStart"));
        date.setDateEnd(request.getParameter("dateEnd"));
        date.setDateFinish(request.getParameter("dateFinish"));

        return date;
    }

    /**
     * 创建新日程
     * 需要传入用户 id
     */
    public void createNewDate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");

        // 获取日程信息
        Date tDate = getDateByRequest(request);

        // 创建新日程并记录消息
        Date date = new Date();
        String message;
        if (dateService.isTimeClash(tDate.getUserId(), tDate.getDateStart(), tDate.getDateEnd())) {
            // 在时间上有冲突，则不能创建日程
            message = "日程时间冲突！";
        } else {
            // 没有冲突则创建日程
            date = dateService.createNewDate(tDate.getUserId(), tDate.getDateName(), tDate.getDateContent(),
                    tDate.getDateClass(), tDate.getDateLevel(), tDate.getDateStart(), tDate.getDateEnd());

            if (date != null) {
                message = "创建日程成功！";
            } else {
                // 创建失败，采用空数据
                date = new Date();
                message = "服务器繁忙，创建日程失败！";
            }
        }

        // 返回数据给前端
        servletLogger.info("【创建日程请求】["+ message +"]" + tDate);
        dateLogger.info("用户[id=" + date.getUserId() + "] ：" + message);
        response.getWriter().write(JsonUtil.dataJson(date, "message", message));
    }

    /**
     * 获取用户所有日程信息
     */
    public void getUserDate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");

        // 获取用户 id，并查询到其所有的日程
        int userId = Integer.parseInt(request.getParameter("userId"));
        servletLogger.info("【查询用户日程请求】目标用户 id：" + userId);
        List<Date> dateList = dateService.findDateByUserId(userId);

        // 反馈前端
        ObjectMapper mapper = new ObjectMapper();
        dateLogger.info("查询到用户[id=" + userId + "] 的所有日程数：" + dateList.size());
        response.getWriter().write(mapper.writeValueAsString(dateList));
    }

    /**
     * 更新日程信息
     * 需要传入日程 id与日程完成
     */
    public void updateDate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");

        // 获取日程信息
        Date tDate = getDateByRequest(request);

        // 更新日程
        servletLogger.info("【更新日程请求】" + tDate);
        boolean success = dateService.updateDate(tDate.getDateId(), tDate.getDateName(),
                tDate.getDateContent(), tDate.getDateClass(), tDate.getDateLevel(),
                tDate.getDateStart(), tDate.getDateEnd(), tDate.getDateFinish());

        // 反馈前端
        if (success) {
            dateLogger.info("日程[id=" + tDate.getDateId() + "] 更新成功");
            response.getWriter().write("success");
        } else {
            dateLogger.info("日程[id=" + tDate.getDateId() + "] 更新失败");
            response.getWriter().write("error");
        }
    }

    /**
     * 删除日程信息
     * TODO 删除日程将将减去该日程所获得的积分
     */
    public void deleteDate(HttpServletRequest request, HttpServletResponse response) throws IOException {

    }

    /**
     * 获取当前需要完成的日程
     */
    public void getCurrentDate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");

        // 获取用户 id，然后获取当前需要完成的日程
        int userId = Integer.parseInt(request.getParameter("userId"));
        Date date = dateService.getCurrentDate(userId);

        // 返回给前端

    }
}
